<!-- src/components/WebSocketDemo.vue -->
<template>
  <div class="websocket-demo">
    <div class="status">
      WebSocket状态:
      <span :class="{ 'connected': isConnected, 'disconnected': !isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </span>
      <el-button
        size="small"
        :type="isConnected ? 'danger' : 'primary'"
        @click="handleConnection"
      >
        {{ isConnected ? '断开连接' : '连接' }}
      </el-button>
    </div>

    <div class="messages">
      <h3>接收到的消息:</h3>
      <div class="message-list">
        <div v-if="messages.length === 0" class="no-messages">
          暂无消息
        </div>
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <div class="message-type">{{ getTypeLabel(message.type) }}</div>
          <div class="message-content">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';

export default {
  name: 'WebSocketDemo',

  data() {
    return {
      isConnected: false,
      messages: [],
      // 消息类型映射表
      typeLabels: {
        [this.$wsMessageTypes.NOTIFY]: '通知',
        [this.$wsMessageTypes.CHAT]: '聊天',
        [this.$wsMessageTypes.ORDER_UPDATE]: '订单更新',
        [this.$wsMessageTypes.SYSTEM]: '系统消息'
      }
    };
  },

  created() {
    // 初始化连接状态
    this.isConnected = this.$websocket.isConnected();

    // 注册各种消息监听器
    this.removeListeners = [
      // 系统消息监听
      this.$websocket.on(this.$wsMessageTypes.SYSTEM, this.handleSystemMessage),

      // 通知消息监听
      this.$websocket.on(this.$wsMessageTypes.NOTIFY, this.handleNotifyMessage),

      // 聊天消息监听
      this.$websocket.on(this.$wsMessageTypes.CHAT, this.handleChatMessage),

      // 订单更新消息监听
      this.$websocket.on(this.$wsMessageTypes.ORDER_UPDATE, this.handleOrderUpdateMessage)
    ];
  },

  beforeDestroy() {
    // 清理所有监听器
    if (this.removeListeners) {
      this.removeListeners.forEach(remove => remove());
    }
  },

  methods: {
    // 处理连接按钮点击
    handleConnection() {
      if (this.isConnected) {
        this.$websocket.close();
        this.isConnected = false;
      } else {
        const token = getToken();
        if (token) {
          this.$websocket.connect(token, () => {
            this.isConnected = true;
            this.$message.success('WebSocket连接成功');
          }, () => {
            this.$message.error('WebSocket连接失败');
          });
        } else {
          this.$message.warning('请先登录');
        }
      }
    },

    // 获取消息类型标签
    getTypeLabel(type) {
      return this.typeLabels[type] || type;
    },

    // 添加消息到列表
    addMessage(type, content) {
      this.messages.unshift({
        type,
        content: typeof content === 'object' ? JSON.stringify(content) : content,
        time: new Date().toLocaleTimeString()
      });

      // 最多保留50条消息
      if (this.messages.length > 50) {
        this.messages.pop();
      }
    },

    // 处理系统消息
    handleSystemMessage(content) {
      this.addMessage(this.$wsMessageTypes.SYSTEM, content);
      // 可以在这里添加系统消息的特殊处理逻辑
    },

    // 处理通知消息
    handleNotifyMessage(content) {
      this.addMessage(this.$wsMessageTypes.NOTIFY, content);
      // 显示通知
      this.$notify({
        title: '新通知',
        message: content.message || JSON.stringify(content),
        type: 'info'
      });
    },

    // 处理聊天消息
    handleChatMessage(content) {
      this.addMessage(this.$wsMessageTypes.CHAT, content);
      // 可以在这里添加聊天消息的特殊处理逻辑
    },

    // 处理订单更新消息
    handleOrderUpdateMessage(content) {
      this.addMessage(this.$wsMessageTypes.ORDER_UPDATE, content);
      // 可以在这里添加订单更新的特殊处理逻辑
    }
  }
};
</script>

<style scoped>
.websocket-demo {
  padding: 20px;
}

.status {
  margin-bottom: 20px;
}

.connected {
  color: #67C23A;
  font-weight: bold;
}

.disconnected {
  color: #F56C6C;
  font-weight: bold;
}

.messages {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 10px;
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
}

.no-messages {
  color: #909399;
  text-align: center;
  padding: 20px;
}

.message-item {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  background-color: #F5F7FA;
  border-left: 4px solid #909399;
}

.message-item.system {
  border-left-color: #909399;
}

.message-item.notify {
  border-left-color: #E6A23C;
}

.message-item.chat {
  border-left-color: #409EFF;
}

.message-item.orderUpdate {
  border-left-color: #67C23A;
}

.message-type {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  word-break: break-all;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: right;
}
</style>
